package com.cgbl.cg.vm.order

import android.app.Application
import android.os.Bundle
import android.text.TextUtils
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import api.ShopServiceFactory
import com.alibaba.fastjson.JSON
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.configs.AppConstants
import com.robot.base.model.*
import com.robot.base.util.ActivityUtils
import com.robot.base.util.LiveDataEventManager
import com.robot.base.util.ToastUtils
import com.robot.base.util.arouter.ARouterUtil
import com.robot.base.utils.PayUtils
import com.robot.base.utils.json.JSONParseUtils
import com.tencent.mm.opensdk.modelpay.PayReq
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent
import me.goldze.mvvmhabit.http.BaseResponse

class ConfirmOrderViewModel(application: Application) : GLBaseViewModel(application) {
    val vipPay = ObservableField(false)
    val uc = UiChangeEvent()

    val payType = ObservableInt(PAY_WECHAT)

    val payTotalField = ObservableField<String>()

    val couponTotalField = ObservableField<String>()

    val vipCouponTotalField = ObservableField<String>()

    val needPayTotalField = ObservableField<String>()

    val payButtonField = ObservableField<String>()

    val couponTitleField = ObservableField("选择优惠券")

    val hasVipCouponField = ObservableBoolean(false)

    val hasCouponField = ObservableBoolean(false)

    val clickSelectCouponCommand = BindingCommand<Any>(BindingAction {
        uc.showSelectCouponPop.postValue("")
    })

    val clickPayCommand = BindingCommand<Any>(BindingAction {
        balanceOrder()
    })

    val clickSelectedAlipayCommand = BindingCommand<Any>(BindingAction {
        payType.set(PAY_ALIPAY)
    })

    val clickSelectedWechatCommand = BindingCommand<Any>(BindingAction {
        payType.set(PAY_WECHAT)
    })

    var tradeNo = ""

    var products = mutableListOf<CheckOrderIdsBean>()

    var selectCoupon: CouponBean? = null

    class UiChangeEvent {
        val showSelectCouponPop: SingleLiveEvent<String> = SingleLiveEvent()

        val refreshGoodsEvent: SingleLiveEvent<List<ConfirmOrderProductBean>> = SingleLiveEvent()

        val refreshCouponEvent: SingleLiveEvent<List<CouponBean>> = SingleLiveEvent()

    }

    fun initParams(ids: List<CheckOrderIdsBean>) {
        this.products = ids as MutableList<CheckOrderIdsBean>
    }

    fun setCoupon(coupon: CouponBean) {
        this.selectCoupon = coupon
        couponTitleField.set(coupon.couponTitle)
        checkOrder()
    }

    fun balanceOrder() {
        val ids = products.map { it.projectId }
        val params =
            mapOf("ids" to products, "payType" to payType.get(), "couponId" to selectCoupon?.id)

        ShopServiceFactory.createOrder(params)
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<String>>(this) {
                override fun onNext(t: BaseResponse<String>) {
                    if (payType.get() == 1) {
                        PayUtils.aliPay(ActivityUtils.getTopActivity(),
                            t.data.toString(),
                            object : Observer<Int> {
                                override fun onSubscribe(d: Disposable) {

                                }

                                override fun onError(e: Throwable) {
                                    ToastUtils.showShort("支付失败!")
                                    ARouterUtil.goToActivityWithBundle(AppConstants.Router.Mine.A_MINE_PAY_RESULT,
                                        Bundle().apply {
                                            putInt(
                                                AppConstants.BundleKey.PAY_RESULT,
                                                PayUtils.PAY_CANCEL
                                            )
                                            putInt(
                                                AppConstants.BundleKey.ORDER_TYPE,
                                                AppConstants.BundleValue.ORDER_TYPE_COURSE
                                            )
                                        })
                                    finish()
                                }

                                override fun onComplete() {

                                }

                                override fun onNext(t: Int) {
                                    if (t == PayUtils.PAY_CANCEL) {
                                        //支付成功
                                        ARouterUtil.goToActivityWithBundle(AppConstants.Router.Mine.A_MINE_PAY_RESULT,
                                            Bundle().apply {
                                                putInt(
                                                    AppConstants.BundleKey.PAY_RESULT,
                                                    PayUtils.PAY_CANCEL
                                                )
                                                putInt(
                                                    AppConstants.BundleKey.ORDER_TYPE,
                                                    AppConstants.BundleValue.ORDER_TYPE_COURSE
                                                )
                                            })
                                        finish()
                                        return
                                    }

                                    if (t == PayUtils.PAY_SUCCESS) {
                                        //支付成功
                                        LiveDataEventManager.postPaySuccessEvent()
                                        ARouterUtil.goToActivityWithBundle(AppConstants.Router.Mine.A_MINE_PAY_RESULT,
                                            Bundle().apply {
                                                putInt(
                                                    AppConstants.BundleKey.PAY_RESULT,
                                                    PayUtils.PAY_SUCCESS
                                                )
                                                putInt(
                                                    AppConstants.BundleKey.ORDER_TYPE,
                                                    AppConstants.BundleValue.ORDER_TYPE_COURSE
                                                )
                                            })
                                        finish()
                                    }
                                }

                            })
                        return
                    } else {
                        val order =
                            JSONParseUtils.parse(t.data.toString(), CreateOrderBean::class.java)
                                ?: return
                        tradeNo = order.id.toString()
                        doPay()
                    }
                }
            })
    }

    fun checkOrder() {
        val params = mapOf("ids" to products, "couponId" to selectCoupon?.id)

        ShopServiceFactory.checkOrder(params)
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<CheckOrderBean>>(this) {
                override fun onNext(t: BaseResponse<CheckOrderBean>) {
                    uc.refreshGoodsEvent.postValue(t.data.orderListRespVOList)
                    payTotalField.set(t.data.totalPrice.toString())
                    couponTotalField.set("-" + t.data.couponPrice)
                    vipCouponTotalField.set(t.data.vipPrice.toString())
                    needPayTotalField.set("￥" + t.data.payPrice)
                    payButtonField.set("立即支付￥" + t.data.payPrice)
                    hasVipCouponField.set(t.data.vipPrice != 0.0 && t.data.vipPrice != null)
                    hasCouponField.set(t.data.couponPrice != 0.0 && t.data.couponPrice != null)
                }
            })
    }

    private fun doPay() {
        if (TextUtils.isEmpty(tradeNo)) {
            ToastUtils.showShort("订单号生成失败!")
            return
        }
        val params = mapOf(
            "notifyTime" to TimeUtils.millis2String(System.currentTimeMillis(), "HH:mm:ss"),
            "outTradeNo" to tradeNo,
            "payType" to payType.get(),
            "tradeNo" to tradeNo
        )
        ShopServiceFactory.paySuccess(params)
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<Any>>(this) {
                override fun onNext(t: BaseResponse<Any>) {
                    LiveDataEventManager.postPaySuccessEvent()
                    ARouterUtil.goToActivityWithBundle(
                        AppConstants.Router.Mine.A_MINE_PAY_RESULT,
                        Bundle().apply {
                            putInt(
                                AppConstants.BundleKey.PAY_RESULT, PayUtils.PAY_SUCCESS
                            )
                            putInt(
                                AppConstants.BundleKey.ORDER_TYPE,
                                AppConstants.BundleValue.ORDER_TYPE_COURSE
                            )
                        })
                    finish()
                }
            })
    }

    fun queryCoupon() {
        val params = mapOf("accountId" to "", "couponType" to 0, "status" to 0)
        ShopServiceFactory.userCouponPage(params).subscribe(object :
            AbstractViewModelSubscriber<BaseResponse<PageListBean<CouponBean>>>(this) {
            override fun onNext(t: BaseResponse<PageListBean<CouponBean>>) {
                uc.refreshCouponEvent.postValue(t.data.list)
            }
        })
    }

    companion object {

        const val PAY_ALIPAY = 1

        const val PAY_WECHAT = 0

    }
}